package com.yueshop.order.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.order.config.AlipayTemplate;
import com.yueshop.order.service.OrderService;
import com.yueshop.order.vo.PayAsyncVo;
import com.yueshop.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

//处理支付宝支付功能的 控制类
@Controller
public class PayWebController {

    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    OrderService orderService;


    @GetMapping(value = "/payOrder",produces = "text/html")
    @ResponseBody
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {

       PayVo payVo = orderService.payOrder(orderSn);

       String pay =  alipayTemplate.pay(payVo);
       return pay;
    }



    @GetMapping("orderList.html")
    public String orderListPage(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum, Model model, HttpServletRequest httpServletRequest){
       //httpServletRequest
        //获取数据之后 进行 验证签名 如果订单正确 修改订单状态
        Map<String,Object> params = new HashMap<>();
        params.put("page",pageNum.toString());
        PageUtils page= orderService.queryPageWhithItem(params);
        model.addAttribute("orders",page.getList());
        return "list";
    }



    //支付宝异步通知回调
    @PostMapping("/payed/notify")
    @ResponseBody
    public String  handleAliPayed(PayAsyncVo payAsyncVo,HttpServletRequest request) throws AlipayApiException {
        //1.验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        //2.修改订单状态
        if (signVerified){
            String result =    orderService.handlePayResult(payAsyncVo);
            return result;
        }else {
            System.out.println("签名验证失败.....");
            return "error";
        }

    }


}
